import {
  Button,
  Form,
  Input,
  Select,
} from 'antd';
import React from 'react';
import {connect} from 'umi';

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 4,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 20,
    },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 20,
      offset: 4,
    },
  },
};

const BaseInfoForm = (props) => {

  const {submitting, dispatch} = props;
  const [form] = Form.useForm();

  /* 提交 */
  const onFinish = () => {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });
      dispatch({
        type: 'PUcenter/modifyUserInfo',
        payload: values,
        callback: () => {
          onReset();
          dispatch({type: 'PUcenter/fetchInfo'});
        },
      });
    });
  };

  /* 重置 */
  const onReset = () => {
    form.resetFields();
  };

  return (
    <Form
      {...formItemLayout}
      form={form}
      onFinish={onFinish}
      initialValues={{}}
      style={{maxWidth: 600, padding: '24px 0'}}
      scrollToFirstError
    >
      <Form.Item
        name='mobile' label='手机号码'
        rules={[{required: true, whitespace: true, message: '手机号码不能为空！'}]}
      >
        <Input placeholder={'请输入手机号码'}/>
      </Form.Item>

      <Form.Item
        name='nickname' label='用户昵称'
        rules={[{required: true, whitespace: true, message: '用户昵称不能为空！'}]}
      >
        <Input placeholder={'请输入用户昵称'}/>
      </Form.Item>

      <Form.Item
        name='sex' label='性别'
        rules={[{required: true, message: '请选择性别！'}]}
      >
        <Select placeholder='请选择性别'>
          <Select.Option value='0'>未知</Select.Option>
          <Select.Option value='1'>男</Select.Option>
          <Select.Option value='2'>女</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name='email' label='电子邮箱'
        rules={[
          {type: 'email', message: '电子邮箱格式错误！'},
          {required: false, message: '电子邮箱不能为空！'},
        ]}
      >
        <Input placeholder={'请输入电子邮箱'}/>
      </Form.Item>

      <Form.Item {...tailFormItemLayout}>
        <Button type='primary' loading={submitting} htmlType='submit' style={{marginRight: 8}}>提交</Button>
        <Button htmlType='button' onClick={onReset}>重置</Button>
      </Form.Item>
    </Form>
  );
};

export default connect(({loading}) => {
  return {
    submitting: loading.effects['PUcenter/modifyUserInfo'],
  };
})(BaseInfoForm);
